/*
 * Copyright 2013, David George, Licensed under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.magneato.mvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.magneato.dto.KVResults;
import org.magneato.dto.MagUser;
import org.magneato.dto.Page;
import org.magneato.service.Repository;
import org.magneato.service.TransactionLogger;
import org.magneato.utils.Authorize;
import org.owasp.html.PolicyFactory;
import org.owasp.html.Sanitizers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Handles requests for the application home page.
 */
@Controller
public class CommentController {
	@Autowired
	private Repository repository;
	
	@Autowired
	private TransactionLogger transLogger;
	
	@Value("${totalComments}")
	public static int totalComments;
	
	// default permissions for comments
	@Value("${comments.umask}")
	private long umask;

	private static final Logger logger = LoggerFactory
			.getLogger(CommentController.class);
	
	PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS).and(
			Sanitizers.IMAGES);

	private static final int count = 5;

	/**
	 * Permissions: Comments are a special case. They always have a parent. We
	 * can post if logged in and we have create permission on the parent
	 * 
	 * @param url
	 *            Parent page URL
	 * @param text
	 *            Comment text, can be html
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "postComment.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	public String post(
			@RequestParam(value = "id", required = true) String url,
			@RequestParam(value = "comment", required = true) String text,
			Model model, HttpServletRequest request,
			HttpServletResponse response) {

		// need create permission for user on page to post
		Page parent = repository.getParentForCreate(url);

		Page page = new Page();
		if (umask >= 0) {
			page.setPerms(umask);
		} else {
			page.setPerms(parent.getPerms());
		}
		page.setParent(parent.getUuid());
		page.setName(url);
		page.setTitle(parent.getTitle());
		page.setIpAddr(request.getRemoteAddr());
		MagUser userDetails = Authorize.getUserDetails();
		page.setAuthor(userDetails.getScreenname());
		page.setGroup(Authorize.getPrincipalGroup());
		page.setCreateDate(System.currentTimeMillis());

		text = policy.sanitize(text);
		page.setContent(text);

		repository.addComment(page);
		transLogger.logUpdate(page, "New post");
		
		response.setContentType("application/json; charset=utf-8");
		model.addAttribute("comment", StringEscapeUtils.escapeJava(text));
		model.addAttribute("id", page.getName());
		model.addAttribute("author", page.getAuthor());
		model.addAttribute("date", page.dateString("dd-MMMM-yyyy, hh:mm a"));

		return "sys/comment";
	}

	/**
	 * 
	 * @param model
	 * @param start
	 * @param uri
	 * @return
	 */
	@RequestMapping(value = { "/fetchComments.do" }, /*produces = "text/html; charset=utf-8",*/ method = RequestMethod.GET)
	public String fetch(HttpServletResponse response, Model model, int start, String uri) {
		KVResults<Page> comments = repository.getComments(uri, start, count);
		if (comments != null) {
			model.addAttribute("comments", comments);
		}
/*
		String cred = Authorize.getPrincipal() + ",";
		for (String role :Authorize.getUserRoles()) {
			cred += role + " ";
		}
		
	    Cookie cookie = new Cookie("magUserId", cred);
	    cookie.setMaxAge(5 * 60 * 100);
	    cookie.setPath("/");
	    response.addCookie(cookie);*/
	    response.setContentType("text/html; charset=utf-8");
		model.addAttribute("id", uri);

		return "sys/comments";
	}
}
